package com.example.musicproject_b.config;


import com.alibaba.fastjson.JSON;
import com.example.common.utils.JWTUtils;
import com.example.common.utils.Resultb;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

/*
* 用户密码验证成功，成功结果的处理
* 自定义接口并没有触发
* */
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse,
                                        Authentication authentication) throws IOException, ServletException {
        UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) authentication;
        HashMap<String, String> map = new HashMap<>();
        map.put("username", authenticationToken.getName());
        map.put("authorities", authenticationToken.getAuthorities().toString());
        String token = JWTUtils.getToken(map);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        httpServletResponse.setContentType("text/json;charset=utf-8");
        PrintWriter writer = httpServletResponse.getWriter();
        HashMap<String, String> resultmap = new HashMap<>();
        resultmap.put("token", token);
        writer.write(JSON.toJSONString(new Resultb().success(resultmap)));
        writer.flush();
        writer.close();
    }

}
